package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimeLineService timeLineService;


    @Override
    public void publish(Movement movement) {
        try {
            //保存动态详情
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //查询当前用户好友数据
            Long userId = movement.getUserId();
            ObjectId movementId = movement.getId();
            timeLineService.saveTimeLine(userId,movementId);
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findByUserId(Long userId, int page, int pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query=Query.query(criteria).skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pr=new PageResult(page,pagesize,0l,movements);
        return pr;
    }

    @Override
    public List<Movement> findFriendMovements(int page, int pagesize, Long friendId) {
        //根据friendId构建Criteria对象
        Criteria criteria=Criteria.where("friendId").is(friendId);
        Query query=Query.query(criteria).skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lineList = mongoTemplate.find(query, MovementTimeLine.class);
        //提取id列表
        List<ObjectId> list = CollUtil.getFieldValues(lineList, "userId", ObjectId.class);
        //根据id列表查询动态信息
        Query movementQuery=Query.query(Criteria.where("id").in(list));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象,设置统计参数
        TypedAggregation aggregation= Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        //调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //获取统计结果
        List<Movement> list = results.getMappedResults();
        return list;
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        //根据pids获取movement对象
        Query query=Query.query(Criteria.where("pid").in(pids));
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    @Override
    public Movement findById(String id) {
        return mongoTemplate.findById(id,Movement.class);
    }

    @Override
    public List<Movement> findByUserId(Long id, Integer page, Integer pagesize, String sortOrder, String sortProp, Integer state) {
        Criteria criteria=Criteria.where("userId").is(id);
        Query query= null;
        if (sortOrder.equals("descending")) {
            query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc(sortProp)));
        } else {
            query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.asc(sortProp)));
        }
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }
}
